﻿using System;
using System.Collections.Generic;
using System.Text;
using JsonFx.Internal;

namespace JsonFx
{
  public class Json
  {
    /// <summary>
    /// Converts to type via json serialization/deserialization.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static T Convert<T>(object obj)
    {
      return (T)Convert(obj, typeof(T));
    }

    public static object Convert(object obj, Type type)
    {
      string json = ToJson(obj);
      return ToObject(json, type);
    }

    public static string ToJson(object obj)
    {
      return JsonWriter.Serialize(obj);
    }

    public static object ToObject(string json)
    {
      return JsonReader.Deserialize(json);
    }

    public static T ToObject<T>(string json)
    {
      return (T)ToObject(json, typeof(T));
    }

    public static object ToObject(string json, Type type)
    {
      object result = JsonReader.Deserialize(json, type);
      if (result != null && result.GetType() != type)
      {
        throw new InvalidOperationException(
            string.Format("Json.ToObject: It was requested {0} type but returned {1}. Json = {2}",
            type, result.GetType(), json));
      }
      return result;
    }
  }
}
